var express = require('express');
var path = require('path');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express();
var qs = require('qs');

//var multipart = require('connect-multiparty');
//var multipartMiddleware = multipart();
var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 接收到文件后输出的保存路径（若不存在则需要创建）
        cb(null, 'D:/webstorm/dianshang/PCdesgin/src/images');
    },
    filename: function (req, file, cb) {
        // 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
        cb(null, Date.now() + "-" +file.originalname);
    }
});

// 创建文件夹
var createFolder = function(folder){
    try{
        // 测试 path 指定的文件或目录的用户权限,我们用来检测文件是否存在
        // 如果文件路径不存在将会抛出错误"no such file or directory"
        fs.accessSync(folder);
    }catch(e){
        // 文件夹不存在，以同步的方式创建文件目录。
        fs.mkdirSync(folder);
    }
};

var uploadFolder = './upload/';
createFolder(uploadFolder);

// 创建 multer 对象
var upload = multer({ storage: storage });
//app.use(multipart({uploadDir: }));
//模板引擎
//app.engine('html', require('express-art-template'));

// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
// parse application/x-www-form-urlencoded
//app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//运行跨域
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    next();
});
// 1. 创建连接
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'ywj123',
    database: 'dianshang',
    useConnectionPooling: true,
});

// 2. 连接数据库 打开冰箱门
connection.connect();

//注册
app.post('/addUser',function (req,res) {
    var username = req.body.username;
    var password = req.body.password1;
    var email = req.body.email;
    //console.log(username,password,email);
    var sql = `insert into user (username,password,email) values ('${username}','${password}','${email}')`;
    //console.log(sql);
    connection.query(sql,function (err) {
        if (err){
         console.log(err.message);
         return;
        }else{
            res.json({status:0,message:'注册成功'});
        }
    })
});
//登录
app.post('/checkLogin',function (req,res) {
	//console.log(qs.parse(req.body));
    var username = req.body.username;
    var password = req.body.password;
	console.log(username,password);
    var sql = `SELECT * FROM user WHERE username='${username}' AND password='${password}'`;
    //console.log(sql);
    connection.query(sql,function (err,result) {
        if (err){
            console.log(err.message);
            return;
        }else{
			console.log(result);
			if(result.length === 0){
				console.log("1");
				res.json({status:1,message:'登录失败'});
			}else{
				res.json({status:0,message:'登录成功'});
			}
            //console.log(result)
        }
    })
});

app.get('/getInfo',function (req,res) {
    var id = req.query.id;
    var sql = `SELECT * FROM user WHERE id=${id}`;
    //console.log(sql);
    connection.query(sql,function (err,result) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:result});
            console.log(result)
        }
    })
});
//获取用户列表
app.get('/getAllUser',function (req,res) {
    var sql = `SELECT * FROM manager`;
    //console.log(sql);
    connection.query(sql,function (err,result) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:result});
            console.log(result)
        }
    })
});
//修改密码
app.get('/editpwd',function (req,res) {
    var pwd = req.query.pwd;
    var id = req.query.id;
    var sql = `UPDATE user SET password = '${pwd}' WHERE id = ${id} `;
    //console.log(sql);
    connection.query(sql,function (err,result) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'修改成功'});
            //console.log(result)
        }
    })
});
//获取收货地址
app.get('/getAddress',function (req,res) {
    var id = req.query.id;
    var sql = `SELECT * FROM address WHERE user_id=${id}`;
    //console.log(sql);
    connection.query(sql,function (err,result) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:result});
            //console.log(result)
        }
    })
});
//添加地址
app.post('/addAddress',function (req,res) {
    var user_id = req.body.user_id;
    var address = req.body.address;
    var port = req.body.port;
    var per = req.body.per;
    var sql = `insert into address (user_id,address,port,per) values (${user_id},'${address}','${port}','${per}')`;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'添加成功'});
        }
    })
});
//删除地址
app.get('/deleteAddress',function (req,res) {
    var id = req.query.id;
    var sql = `DELETE FROM address WHERE id = '${id}' `;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'删除成功'});
        }
    })
});
//修改地址
app.post('/editAddress',function (req,res) {
    var id = req.body.id;
    var address = req.body.address;
    var port = req.body.port;
    var per = req.body.per;
    var sql = `UPDATE address SET address = '${address}', port = '${port}', per = '${per}' WHERE id = ${id} `;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'修改成功'});
        }
    })
});
//商品详情
app.get('/getGoods',function (req,res) {
    var page = req.query.page;
    var sql = `select * from good where page=${page}`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:data});
        }
    })
});
app.get('/getGoodDetail',function (req,res) {
    var id = req.query.id;
    var sql = `select * from good where id=${id}`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:data});
        }
    })
});
//添加购物车
app.post('/addToCart',function (req,res) {
        var user_id = req.body.user_id;
        var price = req.body.price;
        var count = req.body.count;
        var title = req.body.title;
        var selected = req.body.selected;
        var size = req.body.size;
        var good_id = req.body.good_id;
        console.log(good_id)
        var sql1 = `select * from cart where good_id = ${good_id}`;
        connection.query(sql1,function (err,data) {
            console.log(data);
            //并没有考虑相同商品的不同尺码，接口设计不完善
            if(data.length != 0){
                //var data_obj = JSON.parse(data);
                var newCount = parseInt(data[0].count) + parseInt(count);
                console.log(newCount);
                var sql2 = `UPDATE cart SET count = ${newCount} WHERE good_id = ${good_id} `
                connection.query(sql2,function (err,data) {
                    if(err){
                        console.log(err.message);
                        return;
                    }else{
                        res.json({status:0,message:'加入购物车成功'});
                    }
                })
            }else{
                var sql = `insert into cart (user_id,price,count,title,size,selected,good_id) values (${user_id},'${price}',${count},'${title}','${size}','${selected}','${good_id}')`;
                connection.query(sql,function (err,data) {
                    if (err){
                        console.log(err.message);
                        return;
                    }else{
                        res.json({status:0,message:'加入购物车成功'});
                    }
                });
            }
        })
});
app.get('/getCartList',function (req,res) {
    var sql = `select * from cart`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:data});
        }
    })
});
app.get('/deleteCartItem',function (req,res) {
    var id = req.query.id;
    var sql = `DELETE FROM cart WHERE id = '${id}' `;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'删除成功'});
        }
    })
});
//更新状态
app.get('/updateIsDelete',function (req,res) {
    var isDelete = req.query.isDelete;
    var id = req.query.id;
    var sql = `UPDATE manager SET isDelete = '${isDelete}' WHERE id = ${id} `;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            if(isDelete == 0){
                res.json({status:0,message:'禁用成功'});
            }else {
                res.json({status:0,message:'启用成功'});
            }
        }
    })
});
app.get('/getCate1List',function (req,res) {
    var page = req.query.page;
    var sql = `select * from cate1 where page = ${page}`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            var obj ={
                status:0,
                message:data,
            }
            var sql2 = `SELECT COUNT(*) AS NUM FROM cate1`;
            connection.query(sql2,function (err,data) {
                if (err) {
                    console.log(err.message);
                    return;
                }else{
                    obj.total = data;
                    res.json(obj);
                }
            })

        }
    })
});
//添加一级分类
app.get('/addCate1',function (req,res) {
    var newCate1 = req.query.newCate1;
    var sql = `insert into cate1 (name,page) values('${newCate1}',2)`;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'添加成功'});
        }
    })
});
app.get('/getCate2List',function (req,res) {
    var sql = `select * from cate2`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:data});
        }
    })
});
app.get('/getCate1All',function (req,res) {
    var sql = `select * from cate1`;
    connection.query(sql,function (err,data) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:data});
        }
    })
});
app.post('/upload',upload.single('picture'),function (req,res) {
    res.json({status:0,message:req.file.filename});
});
app.post('/addCate2Item',function (req,res) {
    var cate1name = req.body.cate1name;
    var brand = req.body.brand;
    var logo = req.body.logo;
    var sql = `insert into cate2 (cate1name,brand,logo) values('${cate1name}','${brand}','${logo}')`;
    connection.query(sql,function (err) {
        if (err){
            console.log(err.message);
            return;
        }else{
            res.json({status:0,message:'添加成功'});
        }
    })
});
//端口
app.listen(3002,()=>{
    console.log("server is running...");
})